<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018/6/1
 * Time: 11:32
 */

namespace App\Repository;


use App\Category;
use App\Content;
use App\Exceptions\BusinessException;
use App\Exceptions\ValidatorException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class CategoryRepository
{
    /**
     * 增加分类
     *
     * @param array $data
     * @return mixed
     * @throws ValidatorException
     */
    public function store(array $data)
    {
        $this->validtor($data);

        DB::beginTransaction();
        try {
            $cate = Category::create($data);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BusinessException(BusinessException::SERVER_ERROR, '服务器开小差了' . $e->getMessage(), 500);
        }
        return $cate;
    }

    public function index(int $type = 0)
    {
        return Category::query()
            ->where(['p_id' => 0])
            ->when($type != 0, function ($query) use ($type) {
                $query->where('type', $type);
            })
            ->with('children')->get();
    }

    public function content(Request $request)
    {
        $type = $request->input('type', 'law');
        $params = $request->input('title');
        $typeNum = [
            'law' => 10,
            'system' => 20,
            'grade' => 30,
            'peccancy' => 40,
            'proposal' => 50,
            'audit' => 60
        ];
        // $cate = Category::query()->where(['type' => $typeNum[$type], 'p_id' => 0])->with(['content' => function ($query) use ($params) {
        //     $query->orderBy('sort', 'desc')->when(!empty($params), function ($query) use ($params) {
        //         $query->where('content', 'like', '%'.$params. '%');
        //     });
        // }])->get();
        $category = Category::query()
        ->where(['type' => $typeNum[$type], 'p_id' => 0])
        ->with(['child' => function ($query) use ($params) {
            $query->with(['content' => function ($query) use ($params) {
                $query->orderBy('sort', 'desc')->when(!empty($params), function ($query) use ($params) {
                    $query->where('content', 'like', '%'.$params. '%');
                });
            }]);
        }])->get();

        return $category;
    }

    public function getChild($category, $title)
    {
        $cate = [];
        foreach ($category as $key => $v) {
            $cate[$key] = [
                'id' => $v['id'],
                'title' => $v['title']
            ];
            $data = Category::query()->where(['p_id' => $v['id']])->select(['id', 'title'])->get();
            if ($data->count() <= 0) {
               $cate[$key]['content'] = $this->getContents($v['id'], $title);
            } else {
                $cate[$key]['content'] = $data;
               
                foreach ($data as $cate => $c) {
                    $cate[$key]['content'][$cate]['content'] = $this->getContents($c['id'], $title);
                }
            }
        }
        return $cate;
    }

    public function getContents($id, $title)
    {
        return Content::query()
        ->where(['c_id' => $id])
        ->when(!empty($title), function ($query) use ($title) {
            $query->where(['title', 'like', '%' . $title . '%']);
        })->select(['id', 'title', 'content'])->get();
    }

    /**
     * 修改分类
     *
     * @param array $data
     * @param Category $category
     * @return bool
     */
    public function update(array $data, Category $category)
    {
        try {
            $cate = $category->update($data);
        } catch (\Exception $e) {
            throw new BusinessException(BusinessException::SERVER_ERROR, '服务器开小差了', 500);
        }
        return $cate;
    }

    /**
     * 删除分类
     *
     * @param Category $category
     * @return string
     * @throws \Exception
     */
    public function destroy(Category $category)
    {
        $count = $category->children->count();
        if ($count) {
            throw new BusinessException(BusinessException::PARAMETER_ERROR, '请先删除下级分类');
        }

        $category->delete();
        return '删除成功';
    }

    /**
     * 表单验证
     *
     * @param array $data
     * @return bool
     * @throws ValidatorException
     */
    private function validtor(array $data)
    {
        $validator = Validator::make($data, [
            'title' => 'required',
            'type' => 'required',
        ], [
            'required' => ':attribute 不能为空',
        ], [
            'title' => '分类名称',
            'type' => '分类'
        ]);

        if ($validator->fails()) {
            throw new ValidatorException($validator);
        }
        return true;
    }
}
